共计 1264 个字符,预计需要花费 4 分钟才能阅读完成。
客户端:微信小程序
服务器:eggjs+egg-socket.io
弄清楚几个概念。
namespace
// client
import io from 'weapp.socket.io';
// 请求服务器的 'chat' namespace
const server = io('ws://localhost:7001/chat', {
transports: ['websocket'],
});
// server
// 监听 'chat' namespace下的 one-event-name 事件
app.io.of('chat').route('one-event-name', xxx);
path
这个相当于http的请求路径。
// client
const server = io('ws://localhost:7001/chat', {
path: '/socket', // default: socket.io
transports: ['websocket'],
});
// server based on eggjs
config.io = {
init: {
path: '/socket',
},
};
// server based on socket.io directly
const Server = require('socket.io');
const io = Server({
path: '/socket',
serveClient: false
});
在服务端需要根据这个path做反向代理,比如:
location /socket {
proxy_pass socket_server_address; // 支持socket协议的服务
}
使用的时候,约定好namespace
,一般应用用一个namespace就可以。多个namespace
可以使用同一个socket连接,也可以使用多个:
// @see https://github.com/socketio/socket.io-client/blob/master/docs/API.md
// By default, a single connection is used when connecting to different namespaces (to minimize resources):
const socket = io();
const adminSocket = io('/admin');
// a single connection will be established
// That behaviour can be disabled with the forceNew option:
const socket = io();
const adminSocket = io('/admin', { forceNew: true });
// will create two distinct connections
// Note: reusing the same namespace will also create two connections
const socket = io();
const socket2 = io();
// will also create two distinct connections
正文完